// pages/addBook/addBook.js
import {
  Toast,
  Loading
} from "../../../utils/util";
import dayjs from '../../../utils/dayjs'
import echarts from '../../../ec-canvas/echarts'
let chartSearch = {}
async function initChartOne(canvas, width, height, dpr) {
  console.log(chartSearch)
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // 像素
  });
  canvas.setChart(chart);
  const res = await wx.cloud.database().collection('bill').where({
    ...chartSearch,
    type: 1
  }).get()
  const groupedData = res.data.reduce((acc, obj) => {
    const key = wx.getStorageSync('dictList').filter(item => item.dictValue == 'inCome')[0]['dictJson'].filter(it => it.value == obj.cateId)[0]['key'];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  }, {});
  console.log(groupedData, '外部')
  let optionArray = [];
  Object.keys(groupedData).forEach(item => {
    let arr = groupedData[item].map(items => parseInt(items.price))
    let prices = arr.reduce(function (accumulator, currentValue) {
      return accumulator + currentValue;
    }, 0)
    optionArray.push({
      name: item,
      value: prices
    })
  })
  console.log(optionArray, '外部2')
  var option = {
    title: {
      text: `${chartSearch.year}-${chartSearch.month} 收入占比`,
      subtext: '各收入类型',
      left: 'center',
      top: "0"
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)' // 默认显示数值和百分比
    },
    legend: {
      left: 'center',
      top: '50px'
    },
    label: {
      show: true,
      formatter: '{b}: {c} \n({d}%)', // 显示名称、数值、百分比
      position: 'outside',
      color: 'black'
    },
    series: [
      {
        name: '占比',
        type: 'pie',
        radius: '50%',
        data: [...optionArray],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  chart.setOption(option);
  return chart;
}
async function initChartTwo(canvas, width, height, dpr) {
  console.log(chartSearch)
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // 像素
  });
  canvas.setChart(chart);
  const res = await wx.cloud.database().collection('bill').where({
    ...chartSearch,
    type: 2
  }).get()
  const groupedData = res.data.reduce((acc, obj) => {
    const key = wx.getStorageSync('dictList').filter(item => item.dictValue == 'expenditure')[0]['dictJson'].filter(it => it.value == obj.cateId)[0]['key'];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  }, {});
  console.log(groupedData, '外部a')
  let optionArray = [];
  Object.keys(groupedData).forEach(item => {
    let arr = groupedData[item].map(items => parseInt(items.price))
    let prices = arr.reduce(function (accumulator, currentValue) {
      return accumulator + currentValue;
    }, 0)
    optionArray.push({
      name: item,
      value: prices
    })
  })
  console.log(optionArray, '外部a2')
  var option = {
    title: {
      text: `${chartSearch.year}-${chartSearch.month} 支出占比`,
      subtext: '各支出类型',
      left: 'center',
      top: "0"
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)' // 默认显示数值和百分比
    },
    label: {
      show: true,
      formatter: '{b}: {c} \n({d}%)', // 显示名称、数值、百分比
      position: 'outside',
      color: 'black'
    },
    legend: {
      left: 'center',
      top: '50px'
    },
    series: [
      {
        name: '占比',
        type: 'pie',
        radius: '50%',
        data: [...optionArray],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  chart.setOption(option);
  return chart;
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ecOne: {
      onInit: {}
    },
    ecTwo: {
      onInit: {}
    },
    type: 1,
    modalName: "",
    inCome: 0,
    expenditure: 0,
    pickerList: [],
    searchTime: dayjs(new Date()).format('YYYY-MM'),
    form: {
      cateId: "",
      price: 0,
      type: 1,
      time: dayjs(new Date()).format('YYYY-MM-DD')
    },
    billList: [],
    iconList: [{
      icon: 'moneybagfill',
      color: 'green',
      name: '添加收入'
    }, {
      icon: 'sponsorfill',
      color: 'red',
      name: '添加支出'
    }, {
      icon: 'rankfill',
      color: 'pink',
      name: '收入支出占比'
    }],
    // , {
    //   icon: 'formfill',
    //   color: 'orange',
    //   name: '收入支出管理'
    // }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      pickerList: wx.getStorageSync('dictList').filter(item => item.dictValue == 'inCome')[0]['dictJson'].map(item => item.key) ?? [],
    })
    this.getBillList()
  },
  async getBillList() {
    chartSearch = {
      userId: wx.getStorageSync('uid'),
      year: this.data.searchTime.split('-')[0],
      month: this.data.searchTime.split('-')[1]
    }
    const res = await wx.cloud.database().collection('bill').where({
      userId: wx.getStorageSync('uid'),
      year: this.data.searchTime.split('-')[0],
      month: this.data.searchTime.split('-')[1]
    }).get()
    let billList = []
    let dictValue
    res.data.forEach(item => {
      dictValue = item.type == "1" ? 'inCome' : 'expenditure';
      billList.push({
        ...item,
        cateName: wx.getStorageSync('dictList').filter(item => item.dictValue == dictValue)[0]['dictJson'].filter(it => it.value == item.cateId)[0]['key']
      })
    })
    this.setData({
      inCome: billList.filter(item => item.type == '1').map(it => parseInt(it.price)).reduce(function (accumulator, currentValue) {
        return accumulator + currentValue;
      }, 0),
      expenditure: billList.filter(item => item.type == '2').map(it => parseInt(it.price)).reduce(function (accumulator, currentValue) {
        return accumulator + currentValue;
      }, 0),
      billList: [...billList],
      "ecOne.onInit": initChartOne,
      "ecTwo.onInit": initChartTwo
    })
  },
  checkType(e) {
    let target = e.target.dataset.value;
    this.setData({
      type: target
    })
  },
  formSubmit(e) {
    let that = this;
    let formDate = that.data.form;
    console.log(formDate, e)
    if (e.detail.value.price == "0") {
      Toast("none", "金额不能为空");
      return;
    }
    wx.cloud.database().collection('bill').add({
      data: {
        ...formDate,
        price: e.detail.value.price,
        userId: wx.getStorageSync('uid'),
        year: formDate['time'].split('-')[0],
        month: formDate['time'].split('-')[1],
        date: formDate['time'].split('-')[2]
      },
      success(res) {
        Toast("none", "添加成功");
        that.hideModal()
        that.getBillList()
      },
      fail(res) {
        Toast("none", "添加失败");
      },
    })
  },
  openFunction(e) {
    let icon = e.target.dataset['index'];
    console.log(icon)
    switch (icon) {
      case 'moneybagfill':
        this.setData({
          "form.cateId": 1,
          "form.type": 1,
          modalName: "bottomModal",
          pickerList: wx.getStorageSync('dictList').filter(item => item.dictValue == 'inCome')[0]['dictJson'].map(item => item.key),
        })
        break;
      case 'sponsorfill':
        this.setData({
          "form.cateId": 1,
          "form.type": 2,
          modalName: "bottomModal",
          pickerList: wx.getStorageSync('dictList').filter(item => item.dictValue == 'expenditure')[0]['dictJson'].map(item => item.key),
        })
        break;
      case 'formfill':
        break;
      case 'rankfill':
        console.log(666)
        this.setData({
          modalName: "chartModal",
        })
        break;
    }
  },
  PickerChange(e) {
    this.setData({
      'form.cateId': e.detail.value
    })
  },
  DateChange(e) {
    console.log(e);
    this.setData({
      'form.time': e.detail.value
    })
  },
  DateChangePlus(e) {
    console.log(66)
    this.setData({
      searchTime: dayjs(e.detail.value).format('YYYY-MM')
    })
    this.getBillList()
  },
  hideModal() {
    this.setData({
      modalName: '',
      'form.cateId': '',
      'form.price': 0,
      'form.type': 1,
      'form.time': dayjs(new Date()).format('YYYY-MM-DD')
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})